package com.caffeinatedbliss.nanowrimo.spike;

import com.caffeinatedbliss.nanowrimo.NanoWebserviceUtils;
import org.nanowrimo.ws.NanowrimoWebServiceAPI;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Paul Hawke
 * Date: Jun 18, 2006
 * Time: 6:01:42 PM
 * To change this template use File | Settings | File Templates.
 */
public class NanowrimoMiniGraph extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String goalStr = request.getParameter("goal");
    int goal = 50000;
    if (goalStr != null) {
      try {
        goal = Integer.parseInt(goalStr);
      } catch (NumberFormatException e) {
      }
    }

    MiniGraph graph;
    StringTokenizer tok = new StringTokenizer(NanoWebserviceUtils.getFilename(request), "-.");
    String uid = tok.hasMoreTokens() ? tok.nextToken() : null;
    if (uid != null) {
      NanowrimoWebServiceAPI api = new NanowrimoWebServiceAPI();
      try {
        graph = new MiniGraph(api.getUserSummary(Integer.parseInt(uid)).getWordcount(), goal);
      } catch (NumberFormatException e) {
        graph = new MiniGraph("", goal);
      }
    } else {
      String history = request.getParameter("history");
      graph = new MiniGraph(history, goal);
    }
    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(graph.getGraphImage(), "png", os);
    os.close();
  }
}
